package org.quadraspace.filter;

import org.apache.commons.logging.Log;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import org.apache.commons.logging.LogFactory;

/**
 * Interceptor-like class to replace the HTTP Method. It is a commodity adaptation
 * of the QuadraSpace protocol to enable devices that do not have direct
 * support to HTTP method other that GET and POST.
 * 
 * @author Emanuele Di Saverio (emanuele.disaverio at gmail.com)
 *
 */
public class MethodReplacerFilter implements ContainerRequestFilter {
	private static final String ENABLE_HEADER = "X-QuadraSpace-Ex";
	private static final String ENABLE_VALUE = "enable";
	private static final String REPLACE_METHOD_HEADER = "X-QuadraSpace-Method";
	private static Log logger = LogFactory.getLog(MethodReplacerFilter.class);
	public ContainerRequest filter(ContainerRequest req) {
		String header = req.getHeaderValue(ENABLE_HEADER);
		if (header != null && header.equals(ENABLE_VALUE)) {
			logger.trace("found method replacer header> "+ENABLE_HEADER+":"+header);
			String methodToReplace = req.getHeaderValue(REPLACE_METHOD_HEADER);
			logger.trace("replacing with method "+methodToReplace);
			if (methodToReplace != null) {
				req.setMethod(methodToReplace);
			}
		}
		return req;
	}

}
